#include <iostream>
#include <pthread.h>
#include <unistd.h>
using namespace std;

// 5个读进程 3个写进程

int num;
pthread_rwlock_t rwlock;
void *fun_read(void *arg)
{
    int idx = (int)(long)arg;

    while (1)
    {
        pthread_rwlock_rdlock(&rwlock);
        printf("进程%d 读取num的值：%d\n", idx, num);
        // 睡觉1~3秒

        pthread_rwlock_unlock(&rwlock);
        sleep(rand() % 3 + 1);
    }
    return NULL;
}

void *fun_write(void *arg)
{
    int idx = (int)(long)arg;

    while (1)
    {
        pthread_rwlock_wrlock(&rwlock);
        num++;
        printf("进程%d 修改num的值：%d\n", idx, num);
        pthread_rwlock_unlock(&rwlock);
        sleep(rand() % 3 + 1);
    }
    return NULL;
}
int main()
{
    pthread_t tid[8];
    // 添加睡眠种子
    srand(getpid());

    pthread_rwlock_init(&rwlock, NULL);
    for (int i = 1; i <= 8; i++)
    {
        if (i <= 5)
        {
            pthread_create(&tid[i], NULL, fun_read, (void *)(long)i);
        }
        else
        {
            pthread_create(&tid[i], NULL, fun_write, (void *)(long)i);
        }
    }

    for (int i = 1; i <= 8; i++)
    {
        pthread_join(tid[i], NULL);
    }
    pthread_rwlock_destroy(&rwlock);
    return 0;
}